Writing a mini-language with haskell, trouble with "while" statements and blocks { }
Posted
by
Nibirue
on Stack Overflow
See other posts from Stack Overflow
or by Nibirue
Published on 2012-10-14T14:20:22Z
Indexed on
2012/10/14
15:37 UTC
Read the original article
Hit count: 218
haskell
|mini-language
EDIT: problem partially solved, skip to the bottom for update.
I'm writing a small language using haskell, and I've made a lot of progress, but I am having trouble implementing statements that use blocks, like "{ ... }". I've implemented support for If statements like so in my parser file:
stmt = skip +++ ifstmt +++ assignment +++ whilestmt
ifstmt = symbol "if" >>
parens expr >>= \c ->
stmt >>= \t ->
symbol "else" >>
stmt >>= \e ->
return $ If c t e
whilestmt = symbol "while" >>
parens expr >>= \c ->
symbol "\n" >>
symbol "{" >>
stmt >>= \t ->
symbol "}" >>
return $ While c t
expr = composite +++ atomic
And in the Syntax file:
class PP a where
pp :: Int -> a -> String
instance PP Stmt where
pp ind (If c t e) = indent ind ++
"if (" ++ show c ++ ") \n" ++
pp (ind + 2) t ++
indent ind ++ "else\n" ++
pp (ind + 2) e
pp ind (While c t) = indent ind ++
"while (" ++ show c ++") \n" ++
"{" ++ pp (ind + 2) t ++ "}" ++
indent ind
Something is wrong with the while statement, and I don't understand what. The logic seems correct, but when I run the code I get the following error:
EDIT: Fixed the first problem based on the first reply, now it is not recognizing my while statment which I assume comes from this:
exec :: Env -> Stmt -> Env
exec env (If c t e) =
exec env ( if eval env c == BoolLit True then t else e )
exec env (While c t) =
exec env ( if eval env c == BoolLit True then t )
The file being read from looks like this:
x = 1; c = 0;
if (x < 2) c = c + 1; else ;
-- SEPARATE FILES FOR EACH
x = 1; c = 1;
while (x < 10)
{
c = c * x;
x = x + 1;
}
c
I've tried to understand the error report but nothing I've tried solves the problem.
© Stack Overflow or respective owner